<script lang="ts" setup>
import {onMounted, reactive, ref} from "vue";
import axios from "axios";

import 'vue-toast-notification/dist/theme-sugar.css';
import {useToast} from 'vue-toast-notification';

const $toast = useToast();//消息提示栏

const userInfo = reactive({
  headimgurl: '',
  username: '',
  name: '',
  idCard: '',
  bornDate: '',
  sexs: '',
  inputTime: '',
  tel: ''
})
const userInfos = reactive({
  headimgurl: '',
  username: '',
  name: '',
  idCard: '',
  bornDate: '',
  sexs: '',
  inputTime: '',
  tel: '',
  password: ''
})

const token = localStorage.getItem("patient-auth-token")

//获取用户信息
const getUserInfo = () => {
  axios.post("/api/auth/userinfo", {}, {
    headers: {
      token
    }
  }).then(res => {
    console.log(res);
    if (res.data.success) {
      const msg = res.data.message
      userInfo.headimgurl = msg.headimgurl ? msg.headimgurl : '/imgs/noimg.jpg'
      userInfo.username = msg.username ? msg.username : ""
      userInfo.name = msg.name
      userInfo.idCard = msg.identificationCard ? msg.identificationCard : ''
      userInfo.bornDate = msg.bornDate ? msg.bornDate : '未知'
      userInfo.sexs = msg.sexs ? msg.sexs : '未知'
      userInfo.inputTime = msg.inputTime
      userInfo.tel = msg.tel ? msg.tel : ''
    } else {
      window.location.href = "/"
    }
  })
}
const initData = () => {
  getUserInfo()
}
const isShowMyInfo = ref(false)
const showMyInfo = () => {
  isShowMyInfo.value = true
  Object.assign(userInfos, userInfo);
}
const onReset = () => {
  isShowMyInfo.value = false
  userInfos.headimgurl = ''
  userInfos.username = ''
  userInfos.name = ''
  userInfos.idCard = ''
  userInfos.bornDate = ''
  userInfos.sexs = ''
  userInfos.inputTime = ''
  userInfos.tel = ''
  userInfos.password = ''
}
const onSubmit = () => {
  console.log(userInfos);
  const data = {
    username: userInfos.username,
    name: userInfos.name,
    password: userInfos.password,
    identificationCard: userInfos.idCard,
    bornDate: userInfos.bornDate,
    sexs: userInfos.sexs,
    tel: userInfos.tel,
    headimgurl: userInfos.headimgurl
  }
  axios.post("/api/auth/update/user", data, {
    headers
  }).then(res => {
    console.log(res)
    if (res.data.success) {
      $toast.open({
        type: "success",
        message: "修改成功",
        position: "bottom-right"
      })
      setTimeout(() => {
        isShowMyInfo.value = false
        initData()
      }, 150)
    } else {
      $toast.open({
        type: "error",
        message: res.data.message,
        position: "bottom-right"
      })
    }
  })

}
const sexOption = ['男', '女']
const loginOut = () => {
  localStorage.removeItem("patient-auth-token")
  $toast.open({
    type: "success",
    message: "退出登录",
    position: "bottom-right"
  })
  window.location.href = "/"
}
const uploadFileData = ref<File | null>(null);
const headers = {
  token: localStorage.getItem("patient-auth-token")
}
const uploadFile = async () => {
  if (!uploadFileData.value) {
    $toast.open({type: 'error', message: '请先选择文件'});
    return;
  }

  const formData = new FormData();
  formData.append('file', uploadFileData.value);

  try {
    const response = await axios.post('/api/upload/img', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        token: localStorage.getItem("patient-auth-token")

      }
    });
    console.log(response);
    const imgUrl = response.data.message;

    userInfos.headimgurl = imgUrl;

    $toast.open({type: 'success', message: '上传成功'});
  } catch (error) {
    $toast.open({type: 'error', message: '上传失败'});
    console.error('上传错误：', error);
  }
};
onMounted(() => {
  initData()
  getCaseData()
  getFreebackData()
  getAppointmentData()
})
setInterval(() => {
  initData()
  getCaseData()
  getFreebackData()
  getAppointmentData()
}, 3000)
const freebackColumns = [
  {
    name: 'contents',
    required: true,
    label: '反馈内容',
    align: 'left',
    field: 'contents',
    format: val => `${val}`,
    sortable: true
  },
  {name: 'inputTime', align: 'center', label: '反馈时间', field: 'inputTime', sortable: true},
  {name: 'status', label: '整改状态', field: 'status', sortable: true},
  {name: 'handlingMeasures', label: '处理措施', field: 'handlingMeasures'},
  {name: 'updateTime', label: '整改时间', field: 'updateTime'},
]
const caseColumns = [
  {
    name: 'name',
    required: true,
    label: 'Dessert (100g serving)',
    align: 'left',
    field: row => row.name,
    format: val => `${val}`,
    sortable: true
  },
  {name: 'calories', align: 'center', label: 'Calories', field: 'calories', sortable: true},
  {name: 'fat', label: 'Fat (g)', field: 'fat', sortable: true},
  {name: 'carbs', label: 'Carbs (g)', field: 'carbs'},
]
const appointmentColumns = [
  {
    name: 'reservationTime',
    required: true,
    label: '预约时间点（到店时间）',
    align: 'left',
    sortable: true,
    field: 'reservationTime'
  },
  {name: 'aneshesiaType', align: 'center', label: '麻醉方式', field: 'aneshesiaType', sortable: true},
  {name: 'status', label: '状态',  field: row => row.status == 1 ? '正常' : '用户已取消', sortable: true},
  {name: 'inputTime', label: '操作时间', field: 'inputTime'},
]

const appointmentRows = ref([])
const freebackRows = ref([])
const caseRows = ref([])
const getAppointmentData = () => {
  axios.post("/api/reservation/listofmy", {}, {headers})
      .then(res => {
        console.log(res);
        appointmentRows.value = res.data.message
      })
}
const getFreebackData = () => {
  axios.post("/api/freeback/listOfMy", {}, {headers})
      .then(res => {
        console.log(res);
        freebackRows.value = res.data.message
      })
}
const getCaseData = () => {
  axios.post("/api/case/listofmy", {}, {headers})
      .then(res => {
        console.log(res);
        caseRows.value = res.data.message
      })
}

</script>

<template>
  <div class="my-main-box">
    <div class="q-pa-md row items-start q-gutter-md w100p">
      <q-card bordered flat style="width: 100%;">
        <div class="d-flex">
          <q-img
              :src="userInfo.headimgurl"
              style="width: 400px;max-height: 60vh;min-height: 300px;margin: 20px;"
          >
            <template v-slot:error>
              <div class="absolute-full flex flex-center">
                Cannot load image
              </div>
            </template>
          </q-img>
          <q-card-section>
            <div class="text-h4">用户信息</div>
            <div class="text-h6 q-mt-sm q-mb-xs">{{
                userInfo.name
              }}({{ userInfo.sexs }})
            </div>
            <div class="text-h6 q-mt-sm q-mb-xs">电话号码：{{ userInfo.tel }}</div>
            <div class="text-caption text-grey">
              创建时间 {{ userInfo.inputTime }}
            </div>
            <div class="text-caption text-grey">
              出生日期 {{ userInfo.bornDate }}
            </div>
            <div style="margin-bottom: 20px;margin-top: 20px;">
              <q-btn color="secondary" icon-right="settings" label="修改个人信息" @click="showMyInfo"/>
            </div>
            <q-btn color="primary" style="width: 200px" @click="loginOut">
              <div class="ellipsis">
                退出登录
              </div>
            </q-btn>
          </q-card-section>

        </div>
        <div style="flex: 1;display: flex;flex-direction: column;margin-right: 20px;margin-left: 20px;">
          <div style="margin-top: 20px;">
            <q-table
                :columns="caseColumns"
                :rows="caseRows"
                row-key="name"
                style="height: 400px;margin-top: 20px;"
                title="个人医疗记录"
            />
            <q-table
                :columns="appointmentColumns"
                :rows="appointmentRows"
                row-key="name"
                style="height: 400px;margin-top: 20px;"
                title="个人预约记录"
            />
            <q-table
                :columns="freebackColumns"
                :rows="freebackRows"
                row-key="name"
                style="height: 400px;margin-top: 20px;"
                title="个人反馈记录"
            />
          </div>
          <div style="height: 80px;"></div>
          <div>

          </div>
          <div style="height: 80px;"></div>
        </div>
      </q-card>
    </div>
    <q-dialog v-model="isShowMyInfo" persistent transition-hide="scale" transition-show="scale">
      <q-card
          style="max-width: 83vw;display: flex;flex-direction: column;align-items: center;min-width: 400px; max-height: 70vh">
        <div class="text-h4" style="margin-top: 30px;margin-bottom: 3vh;text-align: center
">个人信息
        </div>
        <q-separator/>
        <q-form
            class="q-gutter-md"
            style="width: 60vw;margin-left: 10vw;margin-right: 10vw;min-width: 200px"
            @reset="onReset"
            @submit="onSubmit"
        >


          <q-input
              v-model="userInfos.name"
              :rules="[ val => val && val.length > 0 || '请输入你的名字']"
              filled
              label="你的名字"
              lazy-rules
          />

          <q-input
              v-model="userInfos.tel"
              :rules="[
          val => val.length === 11 && val !== '' || '请输入你的手机号'
        ]"
              filled
              label="你的手机号"
              lazy-rules
          />
          <q-select v-model="userInfos.sexs" :options="sexOption" label="性别"/>
          <q-input
              v-model="userInfos.idCard"
              :rules="[
              val => val !== null && val !== '' || '请输入你的你的身份证',
              val => val.length === 18 || '请输入正确的身份证号码'
        ]"
              filled
              label="你的身份证*"
              lazy-rules
          />
          <q-input
              v-model="userInfos.username"
              :rules="[ val => val && val.length > 0 || '请输入你的账号']"
              filled
              label="你的账号"
              lazy-rules
          />
          <q-input
              v-model="userInfos.password"
              :rules="[
          val => val === '' || (val.length >= 6 && val.length < 30) || '密码强度不够，请重新输入'
        ]"
              filled
              label="你的密码*(如果设置了就是重置密码)"
              lazy-rules
              type="password"
          />
          <q-file
              v-model="uploadFileData"
              accept="image/*"
              class="q-mb-md"
              label="上传头像"
              outlined
          >
            <template v-slot:prepend>
              <q-icon name="attach_file"/>
            </template>
          </q-file>

          <q-btn color="primary" label="上传头像" @click="uploadFile"/>

          <q-img
              :src="userInfos.headimgurl || '/imgs/noimg.jpg'"
              class="q-mt-md"
              style="width: 150px; height: 150px; border-radius: 50%"
          />


          <div style="display: flex;align-items: center;justify-content: space-between">
            <q-input v-model="userInfos.bornDate" filled hint="出生日期"
                     style="margin-right: 30px;" type="date"/>
          </div>
          <div style="display: flex;justify-content: center;align-items: center">
            <div style="margin: 40px;">
              <q-btn class="q-ml-sm" color="primary" flat label="取消" style="width: 150px;margin-right: 30px;"
                     type="reset"/>
              <q-btn color="primary" label="提交" style="width: 150px;" type="submit"/>
            </div>
          </div>
        </q-form>
        <q-separator/>
      </q-card>


    </q-dialog>
  </div>
</template>

<style lang="scss" scoped>
.my-main-box {
  width: 100vw;
}

.my-sticky-column-table {
  max-width: 90vw;
  table-layout: fixed; /* 强制表格使用固定布局 */
}

thead tr:first-child th:first-child {
  background-color: #fff;
}

td {
  width: 200px;
  word-wrap: break-word;
  max-width: 200px;
}

td:first-child {
  background-color: #f5f5dc;
}

th:first-child,
td:first-child {
  position: sticky;
  left: 0;
  z-index: 1;
}


</style>
